from Inspect.models import Users
from Inspect import db
from flask import jsonify


class userController:
    def login(**kwargs):
        obj = Users.query.filter_by(phone=kwargs['phone'], password=kwargs['password']).first()
        if obj:
            if obj.to_json()['password'] == kwargs['password']:
                return {
                    "code": "200",
                    "data": obj.to_json()
                }
        else:
            return {
                "code": "201",
                "msg": "账号密码错误"
            }

    def register(**kwargs):
        name = kwargs["name"]
        phone = kwargs["phone"]
        password = kwargs["password"]
        department = kwargs["department"]
        position = kwargs["position"]
        jurisdiction = kwargs["jurisdiction"]
        portrait = kwargs["portrait"]
        code = kwargs["code"]
        obj = Users(name=name, phone=phone, password=password, department=department, position=position,
                    jurisdiction=jurisdiction, portrait=portrait, code=code)
        user = Users.query.filter_by(phone=phone).count()
        if user > 0:
            return {
                "code": "201",
                "msg": "用户已存在"
            }
        else:
            db.session.add(obj)
            db.session.commit()
            return {
                "code": "200",
                "msg": Users.query.filter_by(phone=phone).first().to_json()
            }

    def getList(**kwargs):
        obj = Users.query.all()
        db.session.close()
        t = []
        for a in obj:
            t.append(a.to_json())
        return t
